package com.rpc.netty.heartbeatDetectionByNetty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author 何章怀晓 hezhanghuaixiao
 * @version V1.0
 * @desc
 */
public class HeartbeatDetection {

  public static void main(String[] args) {

    EventLoopGroup bossGrpoup = new NioEventLoopGroup(1);
    EventLoopGroup workerGrpoup = new NioEventLoopGroup();
    try {
      ServerBootstrap serverBootstrap = new ServerBootstrap().group(workerGrpoup, workerGrpoup);
      serverBootstrap.channel(NioServerSocketChannel.class)
          //针对boss 如在服务器端加日志处理
          .handler(new LoggingHandler(LogLevel.INFO))
          //针对worker
          .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
              ChannelPipeline pipeline = ch.pipeline();
              //处理客服间空闲状态处理器
              //参数是多长时间没有读 写 读写和时间单位
              pipeline.addLast(new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));
              //上述handler触发后会调用管道的下一个handler处理
              pipeline.addLast(new HeartbeatDetectionHandler());
            }
          });

      ChannelFuture sync = serverBootstrap.bind(8000).sync();

      System.out.println("服务器启动完毕");
      //监听后期关闭的channel
      sync.channel().closeFuture().sync();

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      bossGrpoup.shutdownGracefully();
      workerGrpoup.shutdownGracefully();
    }


  }

}
